"""add role to users

Revision ID: xxx
Revises: previous_revision_id
Create Date: 2024-03-27 23:30:00

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'xxx'  # 这里会自动生成
down_revision = 'previous_revision_id'  # 需要替换为你的上一个迁移版本ID
branch_labels = None
depends_on = None

def upgrade():
    # 添加 role 字段
    op.add_column('users', sa.Column('role', sa.String(20), nullable=True))
    
    # 将现有用户的 role 设置为 'user'
    op.execute("UPDATE users SET role = 'user' WHERE role IS NULL")
    
    # 将字段设为非空
    op.alter_column('users', 'role',
                    existing_type=sa.String(20),
                    nullable=False,
                    server_default='user')

def downgrade():
    op.drop_column('users', 'role') 